<!DOCTYPE html>  
<?php
/**
 * Author : Ronin 
 */
session_start();
include "statics.php";
include "functions.php";
if (!isset($_SESSION['member_id']))
{
    header("Location: index.php"); // if user not logged in redirect to index page
}
else
{
    /*
     * detect the type of user to make sure he is either an assigned reviewer
     * or the paper author or an organizer assigned to this conference
     */
    $member_id = $_SESSION['member_id'];
    $bAuthor = bIsAuthor($member_id, get_latest_version($_GET['paper_id']));
    $bOrganizer = bIsOrganizer($member_id, $_GET['conference_id']);
    $bReviewer = bIsReviewer($member_id, $_GET['conference_id'], $_GET['paper_id']);
    if (!$bAuthor && !$bOrganizer && !$bReviewer)
        header("Location: index.php");              // if the user is not the author or a reviewer assinged to this paper or an organizer in this conference move to index
}
?>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="shortcut icon" type="image/x-icon" href="menu icons/favicon.ico" />
        <style type="text/css">
            #comments           
            {
                display: none;
                overflow: auto;
                text-align: left;
                position: relative;
                z-index: 20;
            }
            #all_comments
            {
                width: 150px;
                position: absolute;
                float:left;
                z-index: 25;
            }
            body
            {
                background-color: #0B3861;
                font-family:Arial;
                font-size: 0.80em;
                margin: auto;
                text-align: center;
                color: white;
            }
            #article_div
            {
                padding: 5px;
                position: absolute;
                display: block;
            }
            #article
            {
                overflow: auto;
            }
            #new_comment,#rate_div
            {
                display: none;
                padding: 2px;
                position: absolute;
                width: 350px;
                z-index: 30;
            }
            #new_comment
            {
                height: 200px;
            }
            #comment_content
            {
                height: 140px;
                width: 340px;
                overflow: auto
            }
            table
            {
                float: left;
                margin: auto;
            }
            #comments_col,#article_col
            {
                float:left;
            }
            div,select,option,textarea,button
            {
                font-family: Arial;
                text-align: center;
                border-radius: 10px;
                -moz-border-radius: 10px;
                -webkit-border-radius: 10px;
                border: 2px solid #003366;
                border-color: white;
                background-color: #0B3861;
                color:white;
            }
            textarea
            {
                text-align: left;
                resize: none;
            }
            .rate_radio,#rating_label,#submit,#comment_list
            {
                display: none;
            }
            .progress_outer
            {
                text-align: center;
                background-color: white;
                width: 200px;
                height: 5px;
            }
            .progress_inner
            {
                float:left;
                height: 5px;
                width:0px;
                border: 0px;
                border-radius: 2px;
                -moz-border-radius: 2px;
                -webkit-border-radius: 2px;
                background-color: green;
            }
            .criteria_name
            {
                float: right;
            }
        </style>
        <?php include "jquery.php" ?>
        <script type="text/javascript">
            $(document).ready(function () // wait for the document to be ready before running any javascript
            {   
                if(navigator.appName=="Microsoft Internet Explorer" && ((navigator.appVersion.indexOf("MSIE 8.0")!=-1) || navigator.appVersion.indexOf("MSIE 7.0")!=-1))
                {
                    $("head").append("<bgsound loop='1' src='test.mp3'></bgsound>");     // if using old versions of internet explorer prompt the user to upgradefor                                                                      // full functionality
                }                                                                        // full functionality
                span_id=-1;      // initialize span id variable
                last_span=-1;   // variable used to store the id of the last clicked span
                all_ids=[];     // array of span ids used to store the ids of spans during multi paragraph commenting
                comment_ids=[]; // array or span ids used to store the ids of multiple spans when they share a common comment
                /*
                 * repositioning and resizing all controls to fit browser window at any resolution (alpha)
                 */
                windowheight=$(window).height();
                windowwidth=$(window).width();
                $("#article,#article_div").height(windowheight*0.95);
                newcommentheight=$("#new_comment").height();
                $("#comments").height(windowheight*0.95);
                $("#comments").width(300);   
                comments_width=$("#comments").width();  // store the comments div width for further use to save the overhead of calling width() everytime

                /*
                 * resizing and repositioning all controls whenever the browser window is resized (alpha)
                 */
                $(window).resize(function()
                {
                    resize();
                });
                
                /*
                 *modifiying the colors of all rating criteria progress bars depending
                 *on the level of rating for each criteria 75+ is green, 50+ is light brown
                 *25+ is orange and less than 25 is red
                 */
                $(".progress_inner").each(function()
                {
                    if($(this).width()<($(".progress_outer").width())*0.75)
                    {
                        $(this).css("background-color", "#868A08");
                    }
                    if($(this).width()<($(".progress_outer").width())*0.5)
                    {
                        $(this).css("background-color", "orange");
                    }
                    if($(this).width()<($(".progress_outer").width())*0.25)
                    {
                        $(this).css("background-color", "red");
                    }
                });
                $(document).on("mouseenter","li",function()                     // bind all list items to have hover effect now and in the future
                {
                    $(this).css('background-color', 'green');
                    $(this).css('cursor', 'pointer');
                });
                $(document).on("mouseleave","li",function()
                {
                    $(this).css('background-color', '#0B3861');
                    $(this).css('cursor', 'default');
                });
                
                $("#submit_comment").bind("click", function()                   //the action of the submit button
                {
                    article_id= $("#version_id").val();                         // the version_id of the current loaded paper
                    com_con = $("#comment_content").val();                      // the value of the comment placed
                    
                    /*
                     * ajax request to send the newly written comment along with the span id or ids for which this comment
                     * is to be stored, after the response is received the newly commented on spans are highlighted and marked
                     * for future comment retreiving, then the all_ids array is zeroed to avoid commenting on the wrong spans 
                     * later.
                     */
                    if($("#multi_span").html()=="Multiple paragraphs")
                    {
                        if(com_con.length>0)
                        {
                            $.ajax({
                                type:"POST",
                                url: "Comments.php",
                                data:{version_id:article_id,span:all_ids,text:com_con,func:"comment"},
                                success: function(response)
                                {
                                    alert(response);
                                    len=all_ids.length;
                                    for(i=0;i<len;i++)
                                    {
                                        if($("#article").contents().find("span[id="+all_ids[i]+"]").attr("comment")==undefined)
                                        {
                                            $("#article").contents().find("span[id="+all_ids[i]+"]").attr("comment", "true");
                                            $("#article").contents().find("span[id="+all_ids[i]+"]").css("background-color", "#F2F5A9");
                                            $("#article").contents().find("span[id="+all_ids[i]+"]").attr("title", "Click on highlighted text to show comments");
                                        }
                                    }
                                    for(i=0;i<all_ids.length;i++)
                                        repaint(all_ids[i]);
                                
                                    all_ids.length=0;
                                    $("#new_comment").slideUp(300);
                                }
                            });
                            window.onbeforeunload="";                           // remove the prompt given to the user when redirecting away from page
                        }
                        else
                        {
                            alert("please insert comment first");
                        }    
                    }
                    else
                    {
                        alert("If you are done selecting the required paragraphs please click the \'Done selecting\' button before submitting your comment");
                    }

                });
                
                /*
                 * this handler handles commenting on multiple paragraphs
                 * by marking them in grey and storing their ids in the all_ids array
                 * until the user is done selecting all the paragraphs and inserts his
                 * comment to be stored for all of them it also unbinds the regular click
                 * handler for span clicks and replaces it temporarily with one that serves
                 * the multi span comment purpose.in the end the temporary handler is unbound
                 * and the original handler is bound once more
                 */
                $("#multi_span").bind("click",function()
                {
                    if($(this).html()=="Multiple paragraphs")
                    {
                        alert("Please select the paragraphs for this comment");
                        repaint(last_span);
                        $(this).html("Done selecting?");    
                        $("#article").contents().unbind("click");
                        $("#article").contents().find("span").unbind("click");
                        for(i=0;i<all_ids.length;i++)
                            repaint(all_ids[i]);
                        all_ids.length=0;
                        $("#article").contents().find("span").bind("click", function()
                        {
                            id=$(this).attr("id");
                            if($.inArray(id, all_ids)==-1)
                            {
                                all_ids[all_ids.length]=$(this).attr("id");
                                $(this).css("background-color", "grey");  
                            }
                            else
                            {
                                all_ids.splice($.inArray(id, all_ids),1);
                                repaint($(this).attr("id"));
                            }
                        });
                    }
                    else
                    {
                        $(this).html("Multiple paragraphs");
                        $("#article").contents().find("span").unbind("click");
                        autoReposition();
                        bindSpanClick();
                    }
                });
                
                /*
                 *  this handler handles submissions for rating the paper according to the criteria specified by the conference 
                 *  organizer, the function sends the rating value from 1-5 along with the span id for which the rating
                 *  is to be placed
                 */
                $("#submit").bind("click", function()
                {
                    if($("input:radio[name=rating_value]:checked").length)
                    {
                        $.ajax({
                            type: "GET",
                            url: "rating.php", 
                            data: {rate:$("#rate option:selected").val(),rating_value:$("input:radio[name=rating_value]:checked").val(),span:span_id,conference_id:$('#conference_id').val(),version_id:$('#version_id').val(),submit:$('#submit').val()},
                            success: function(response)
                            {
                                alert(response);
                                $('#rate_div').slideUp(300);
                            }
                        });      
                    }
                    else
                    {
                        alert("please select rating value");
                    }
                });
                
                /*
                 * this handler and its callback function retreives all comments for the paper from the 
                 * server and displays them in an ordered list in which each list item is a comment
                 * also the comments are clickable where if a comment is clicked the article automatically scrolls down to span
                 * or spans to which the clicked comment points and highlights it in grey
                 */
                $("#all_comments").click(function()
                {
                    if($(this).html()=="Show all comments")
                    {
                        $("#comment_list").slideUp(300, function()
                        {
                            $("#comment_list").html("");
                            if($("#comments").css("position")!="absolute")
                            {
                                paddedpos=comments_width+10;
                                $("#article_div,#all_comments").animate({left:paddedpos},300);  
                            }
                            $("#comments").slideDown(300, function()
                            {
                                $.ajax({
                                    type: "GET",
                                    url: "Comments.php",
                                    data: {version_id:$("#version_id").val(),conference_id:$("#conference_id").val(),func:"allcomments"},
                                    cache:true,
                                    success: function(response)
                                    {
                                        row=response.split("%%EOR"); // split the response to get each row
                                        len=row.length;
                                        for(i=0;i<len;i++)
                                        {
                                            col=row[i].split("%%EOC");  // split again to get each column
                                            if(col.length==2)
                                            {
                                                flag=false;
                                                $("#comment_list li").each(function()
                                                {
                                                    if($(this).text()==col[0] && $(this).attr("class")!=undefined)  //if the comment alread is assigned to an id append the new id that shares this comment
                                                    {
                                                        cls=$(this).attr("class")+","+col[1];
                                                        $(this).attr("class",cls);
                                                        flag=true;
                                                        return false;
                                                    }    
                                                });
                                                if(!flag)                           // if the comment has not been assigned to an id before assign it and place a list item for it in the comments list
                                                {
                                                    $('#comment_list').append('<li class="'+col[1]+'">'+col[0]+'</li>');  
                                                }
                                            }
                                        }
                                        $("#comment_list").slideDown(300);
                                        $("li").click(function()
                                        {   
                                            len=comment_ids.length; // check if comment_ids has any span ids stored in it revert all of their highlighting to 
                                            if(len>0)               // their original color
                                            {
                                                len=comment_ids.length;
                                                for(i=0;i<len;i++)
                                                    repaint(comment_ids[i]);
                                                    
                                                comment_ids.length=0;
                                            }
                                            if($(this).attr("class").indexOf(",")==-1)
                                            {
                                                element=$("#article").contents().find("span[id="+$(this).attr("class")+"]");    // get the span with the id corresponding to the clicked comment class name
                                                $("#article").contents().find("html,body").animate({scrollTop:$(element).offset().top}, 500);  //scroll down to the span corresponding to the clicked comment
                                                $(element).css("background-color", "grey");
                                                comment_ids[comment_ids.length]=$(element).attr("id");              //place the span id of the clicked span in this array to mark it
                                            }
                                            else
                                            {          
                                                comment_ids=$(this).attr("class").split(",");             // find all span ids that correspond to the current clicked comment
                                                element=$("#article").contents().find("span[id="+comment_ids[0]+"]");
                                                $("#article").contents().find("html,body").animate({scrollTop:$(element).offset().top}, 500); // scroll to the first span in the array
                                                len=comment_ids.length;
                                                for(i=0;i<len;i++)
                                                {
                                                    $("#article").contents().find("span[id="+comment_ids[i]+"]").css("background-color", "grey"); // highlight all spans related to this comment in grey
                                                }
                                            }
                                        });
                                    }
                                });
                                $("#all_comments").html("Hide all comments");
                            });
                        });
                    }
                    else
                    {
                        $("#comment_list").slideUp(300, function()
                        {
                            $("#comment_list").html("");
                            if($("#comments").css("position")!="absolute")                  // if the comments div is absolutely positioned animate the movement of the article div
                                $("#article_div,#all_comments").animate({left:"0"},300);    // to the left most portion of the screen
                                
                            $("#comments").slideUp(300,function()
                            {   
                                $("#all_comments").html("Show all comments");
                                len=comment_ids.length;
                                for(i=0;i<len;i++)  //loop through all comment_ids and revert their highlighting to the original color
                                    repaint(comment_ids[i]);
                                comment_ids.length=0;
                            });
                        });           
                    }
                });
                
                $("#comment_cancel").bind("click",function()
                {
                    $("#new_comment").slideUp(300,function()
                    {
                        len=all_ids.length;
                        for(i=0;i<len;i++)
                            repaint(all_ids[i]);
                        
                        all_ids.length=0;
                        $("#multi_span").html("Multiple paragraphs");
                        $("#article").contents().find("span").unbind("click");
                        autoReposition();
                        bindSpanClick();
                        window.onbeforeunload="";                               // remove the prompt given to the user when redirecting away from page
                    });
                });
                $("#rate_cancel").bind("click", function()
                {
                    $("#rate_div").slideUp(300);
                });
                
                $("#rate").change(function()
                {
                    if($("#rate option:selected").text()!="Rating criteria")        //present the user with the interface to rate the current paragraph
                    {                                                               // according to the chosen rating criteria
                        $("#rating_label").text($("#rate option:selected").text());
                        $("#rating_label").fadeIn(200);
                        $(".rate_radio").fadeIn(200);
                        $("#submit").fadeIn(200);
                    }
                    else
                    {
                        $("#rating_label").fadeOut(200);
                        $(".rate_radio").fadeOut(200);
                        $("#submit").fadeOut(200);
                    }
                });
                
                $("#new_comment,#rate_div").mousedown(function(event)           // implementing the dragging effect only functional in IE9,FF,Chrome
                {                                                               // by getting the mouse position whenever the mouse is pressed over the
                    event.preventDefault();                                     // new_comment or rate_div divs and bind the mouse movement event of the 
                    posXInit=event.pageX;                                       // entire window to get the new mouse position and subtract the old position from
                    posYInit=event.pageY;                                       // the new one and move the top and left dimensions of the div currently being dragged
                    this_element=$(this);                                       // by the same amount, after that the new position becomes the old one and the operation
                    $(window).bind("mousemove",function(event)                  // is repeated until the mouse is either released or leaves the div being dragged
                    {
                        posX=event.pageX;
                        posY=event.pageY;
                        posXMove=posX-posXInit;
                        posYMove=posY-posYInit;
                        posXNew=parseInt($(this_element).css("left"),10)+posXMove;
                        posYNew=parseInt($(this_element).css("top"),10)+posYMove;
                        posXInit=posX;
                        posYInit=posY;
                        $(this_element).css({"top":posYNew,"left":posXNew});  
                    });
                    return false;
                });
                $(window).bind("mouseup",function()
                {
                    $(window).unbind("mousemove");
                });
                $("#comment_content,#rate,#comment_cancel,#submit_comment,#submit,#rate_cancel,#multi_span").bind("mousedown",function(event)
                {
                    event.stopPropagation(); // stop the propagation of the mouse down event from going up the DOM tree to make sure the elements in the selector
                });                          // are not affected by the drag effect in order to ensure their normal functionality
                
                $("#comment_content").bind("keyup input paste",function()       // bind any input change in the comment_content text area to change the number
                {                                                               // of characters left for the comment and also detect when the user hits 2000 characters
                    text=$("#comment_content").val();                           // and prevent him from adding any more since the maxlength attribute is not supported 
                    if(text.length>2000)                                        // in old browsers
                        $("#comment_content").val(text.substr(0,2000));
                    $("#comment_length").html(2000-text.length);
                });
                
                document.getElementById("article").onload=function()            // start binding events as soon as the article is loaded in the iframe
                {
                    resize();                                                   // resize window to fit elements
                    autoReposition();                                           // activate auto repositioning for the new_comment and rate_div divs 
                    $("#article").contents().find("A").contents().unwrap();     // remove all hyperlinks from the article to prevent incorrect redirection (temporary fix)
                    $("#article").contents().find("span").hover(function()      // whenever a span is hovered over by the mouse it shall be outlined with a border
                    {                                                           // in order to know the bounds of the span
                        $(this).css("border", '1px dashed');
                    },function()
                    {
                        $(this).css("border", '');
                    });
                    
                    /*
                     * retrieve the span ids of every span in the loaded article that 
                     * has comments already stored for it in the database then adds a comment attribute to each 
                     * of them to mark them as having been commented on before and highlights it in 
                     * yellow and adds some descriptive tool tip text
                     */
                    $.ajax({
                        type: "GET",
                        url:"Comments.php", 
                        data: {version_id: $('#version_id').val(),conference_id:$("#conference_id").val(),func: "getspans"},
                        success:function(response)                           
                        {                                                    
                            if(response!="failure")                          
                            {                                              
                                span_ids=response.split('%%EOR');           //split the response text at each instance of %%EOR to acquire all span ids and place them in the array called span_ids
                                len=span_ids.length;                
                                for(i=0;i<len;i++)
                                {
                                    $("#article").contents().find("span[id="+span_ids[i]+"]").attr("comment", "true");
                                    $("#article").contents().find("span[id="+span_ids[i]+"]").css("background-color", "#F2F5A9");
                                    $("#article").contents().find("span[id="+span_ids[i]+"]").attr('title', 'Click on highlighted text to show comments');
                                }  
                            }
                            else
                            {
                                alert(response);
                            }
                        }
                    });
                    
                    bindSpanClick(); // bind the click event of each span to the appropriate action
                };
                
            });
        </script>
        <script type="text/javascript">
            function resize()
            {
                if($("#article").contents().find("#div1").width())
                    divwidth=$("#article").contents().find("#div1").width()+30; // resize the article iframe to fit the width of the article or have a width of 800px
                else                                                            // if the article width was not retreived successfully
                    divwidth=800;
                $("#article_div,#article").width(divwidth);
                windowheight=$(window).height();
                windowwidth=$(window).width();
                $("#article_div,#article,#comments").height(windowheight*0.95);
                if((windowwidth-$("#article").width())<300)                     // to handle low resolutions such as 1024*768 whenever the window is resized 
                {                                                               // if the size of the window is not at least 300px more than the width of the article                                 
                    $("#comments").css("position", "absolute");                 // then the comment list is forced to overlap the article whenever opened to save space
                    if($("#article_div").position().left!=0)
                        $("#article_div,#all_comments").css("left", "0");                   
                }
                else
                {
                    $("#comments").css("position", "relative");
                    paddedpos=comments_width+10;
                    if($("#comments").is(":visible"))
                        $("#article_div,#all_comments").css("left",paddedpos);       
                }
            }
            
            function autoReposition()
            {
                $("#article").contents().click(function(event)                  // finds the position inside the article iframe whenever anything inside it is clicked
                {                                                               // and moves the new_comment and rate_div there so whenever the user clicks a span both
                    posArticleLeft=$("#article").offset().left;                 // divs will be in same position of the span
                    posArticleTop=$("#article").offset().top;
                    posCommentBottom=event.pageY+posArticleTop-$(this).scrollTop()+newcommentheight;
                    $("#new_comment").animate({"top":event.pageY+posArticleTop-$(this).scrollTop(),"left":event.pageX+posArticleLeft+$(this).scrollLeft()}, 200);
                    $('#rate_div').animate({"top":posCommentBottom,"left":event.pageX+posArticleLeft},200); 
                });
            }
            
            function repaint(element_id)
            {
                element=$("#article").contents().find("span[id="+element_id+"]");
                if(element.attr("comment")!=undefined)
                    $(element).css("background-color", "#F2F5A9");
                else
                    $(element).css("background-color", "white");
            }
            
            function bindSpanClick()
            {
                $("#article").contents().find("span").bind("click",function() // bind the click event of each span on the page to every action that is required
                {
                    span_id=$(this).attr("id");      // get the id of the clicked span
                    if(all_ids.length>1)
                    {
                        if(!confirm("Are you sure you want to discard you current multi paragraph comment?"))
                        {
                            return;      
                        }
                    }
                    for(i=0;i<all_ids.length;i++)
                        repaint(all_ids[i]);
                    
                    all_ids.length=0;
                    all_ids[0]=span_id;
                    $(this).css("background-color", "#81DAF5");
                    last_span=span_id;
                    if($(this).attr("comment")!=undefined) // check if the span has comments stored in the database for it
                    {
                        $("#comment_list").slideUp(300, function()
                        {
                            if($("#comments").css("position")!="absolute")
                            {
                                paddedpos=comments_width+10;
                                $("#article_div,#all_comments").animate({left:paddedpos},300);  
                            }
                            $("#comments").slideDown(300, function()
                            {
                                $.ajax({
                                    type: "GET",
                                    url:"Comments.php", 
                                    cache:true,
                                    data:{span: span_id,version_id: $('#version_id').val(),conference_id:$("#conference_id").val(),func:"getcomments"},
                                    success: function(response) // retrieve all comments for a specific span denoted by span_id
                                    {
                                        contents=response.split('%%EOR');// split the response text at each instance of %%EOR to get all comments for the specific span and 
                                        len=contents.length;             // place them in the array called contents   

                                        $('#comment_list').html(''); // clear comment list
                                        for(i=0;i<len;i++) // add a list item in the comments list for every comment found in the contents array
                                        {
                                            if(contents[i].length>0)
                                                $('#comment_list').append("<li class="+span_id+">"+contents[i]+"</li>");
                                        }
                                    }
                                });
                                $("#comment_list").slideDown(300,function()
                                {
                                    $("li").click(function()                    // scroll to the corresponding span whenever a comment is clicked
                                    {   
                                        element=$("#article").contents().find("span[id="+$(this).attr('class')+"]");
                                        $("#article").contents().find("html,body").animate({scrollTop:$(element).offset().top}, 500);
                                    }); 
                                    $("#all_comments").html("Hide all comments");
                                });
                                $("#new_comment").slideDown(300);
                                $("#rate_div").slideDown(300);  
                            });
                        });
                    }
                    else
                    {
                        // if the clicked span has no comments stored for it hide the comments div and only show new comments and rating
                        $("#new_comment").slideDown(300);
                        $("#rate_div").slideDown(300); 
                    }
                    window.onbeforeunload=function()                            // add a prompt to the user whenever he tries to leave the page before submitting the
                    {                                                           // comment to ask him for confirmation
                        return "Are you sure you want to leave, any unsaved data will be lost?";
                    }
                });
            }
        </script>
        <title></title>
    </head>
    <body>
        <table>
            <tr>
                <td id="comments_col">
                    <!-- new comment div to insert a new comment for a clicked span -->
                    <br/>
                    <div id="comments">
                        <ol id="comment_list"></ol>
                    </div>
                </td>
                <td id="article_col">
                    <button id="all_comments">Show all comments</button>
                    <br/>
                    <div id="article_div">
                        <!-- internal frame in which the article is loaded -->
                        <iframe id="article" src="<?php
        require_once "functions.php";
        echo "Comments.php?version_id=" . get_latest_version($_GET['paper_id']) . "&func=load";
        ?>"></iframe>  
                    </div>
                    <?php
                    if (bIsReviewer($member_id, $_GET['conference_id'], $_GET['paper_id']))
                    {
                        echo "<div id='new_comment'>
                        <textarea  id='comment_content' name='comment_content' maxlength='2000'></textarea>
                        <label id='comment_length'>2000</label>
                        <br>
                        <button id='submit_comment' name='submit_comment'>Submit comment</button>
                        <button id='multi_span' name='multi_span'>Multiple paragraphs</button>
                        <button id='comment_cancel' name='comment_cancel'>Cancel</button>
                    </div>";

                        echo "<div id='rate_div'>
                            <select name='rate' id='rate'>
                            <option value=''>Rating criteria</option>";
                        $all_criteria = rsSelect("Rate_id", "conference_rating_criteria", array("conference_id=", $_GET['conference_id']));
                        if (!is_string($all_criteria))
                        {
                            $Rating_Criteria = "";
                            while ($row = mysql_fetch_assoc($all_criteria))     // get all the rating criteria for this conference and place then inside the select box
                            {
                                $rsCriteriaName = rsSelect("criteria_type", "rating_criteria", array('rate_id=', $row['Rate_id']));
                                if (!is_string($rsCriteriaName))
                                {
                                    $rowCriteriaName = mysql_fetch_assoc($rsCriteriaName);
                                    $Rating_Criteria .= "<option value={$row['Rate_id']}>{$rowCriteriaName['criteria_type']}</option>";
                                }
                                else
                                    echo $rsCriteriaName;
                            }
                            echo $Rating_Criteria;
                        }
                        else
                            echo $all_criteria;
                        echo "</select>";
                        echo "<br/>
                        <label id = 'rating_label'></label>
                        <label class = 'rate_radio' for = 'radio1'>1</label><input type = 'radio' id = 'radio1' name = 'rating_value' class = 'rate_radio' value = '1'/>
                        <label class = 'rate_radio' for = 'radio2'>2</label><input type = 'radio' id = 'radio2' name = 'rating_value' class = 'rate_radio' value = '2'/>
                        <label class = 'rate_radio' for = 'radio3'>3</label><input type = 'radio' id = 'radio3' name = 'rating_value' class = 'rate_radio' value = '3'/>
                        <label class = 'rate_radio' for = 'radio4'>4</label><input type = 'radio' id = 'radio4' name = 'rating_value' class = 'rate_radio' value = '4'/>
                        <label class = 'rate_radio' for = 'radio5'>5</label><input type = 'radio' id = 'radio5' name = 'rating_value' class = 'rate_radio' value = '5'/>";
                        echo "<br/>
                    <button name = 'submit' id = 'submit'>Rate</button>
                    <button id = 'rate_cancel' name = 'rate_cancel'>Cancel</button>
                    <br/>
                    <label>Average by all users</label>
                    <table>";
                        $rsResult = rsSelect("Rate_id", "conference_rating_criteria", array('conference_id=', $_GET['conference_id']));
                        if (!is_string($rsResult))
                        {
                            while ($row = mysql_fetch_assoc($rsResult))
                            {
                                $rsCriteriaName = rsSelect("criteria_type", "rating_criteria", array('rate_id=', $row['Rate_id']));
                                if (!is_string($rsCriteriaName))
                                {
                                    $rowCriteriaName = mysql_fetch_assoc($rsCriteriaName);
                                    echo "<tr><td class='criteria_name'>" . $rowCriteriaName['criteria_type'] . "</td>";
                                    $rsCountSum = rsSelect(array("COUNT(rate_id)", "SUM(rating_value)"), "version_rating_criteria", array('rate_id=', $row['Rate_id'], 'AND', 'version_id=', get_latest_version($_GET['paper_id'])));
                                    if (!is_string($rsCountSum))
                                    {
                                        $rowCountSum = mysql_fetch_assoc($rsCountSum);
                                        $iCount = $rowCountSum['COUNT(rate_id)'];
                                        $iSum = $rowCountSum['SUM(rating_value)'];
                                        if ($iCount != 0)                           // retreive the average rating for each criteria as it was rated by all other users
                                        {                                           // and advances the progress bar by the average rating value
                                            $dAvg = $iSum / $iCount;
                                            $dBarWidth = ((200 * $dAvg) / 5) . "px";
                                            echo "<td>
                                                    <div class='progress_outer'>
                                                    <div class='progress_inner' style='width: $dBarWidth;'></div>
                                                    </div></td></tr>";
                                        }
                                        else
                                        {
                                            echo"<td><div class='progress_outer'>
                                                    <div class='progress_inner'></div>
                                                    </div></td></tr>";
                                        }
                                    }
                                    else
                                        echo $rsCountSum;
                                }
                                else
                                    echo $rsCriteriaName;
                            }
                            $rsFinalRating = rsSelect("final_rating", "paper", array("paper_id=", $_GET['paper_id']));
                            if (is_string($rsFinalRating))
                                echo $rsFinalRating;
                            else
                            {
                                $row = mysql_fetch_assoc($rsFinalRating);       // get the final rating of the paper and place a progress bar for it

                                $dBarWidth = (($row['final_rating'] * 200) / 5) . "px";
                                echo "<tr><td>Final rating</td>";
                                echo "<td>
                                        <div class='progress_outer'>
                                        <div class='progress_inner' style='width:$dBarWidth;'></div>
                                        </div></td></tr>";
                            }
                        }
                        else
                            echo $rsResult;
                        echo "</table></div>";
                    }
                    else
                    {
                        echo "<div id='rate_div'>
                                <table>";
                        $rsResult = rsSelect("Rate_id", "conference_rating_criteria", array('conference_id=', $_GET['conference_id']));
                        if (!is_string($rsResult))
                        {
                            while ($row = mysql_fetch_assoc($rsResult))
                            {
                                $rsCriteriaName = rsSelect("criteria_type", "rating_criteria", array('rate_id=', $row['Rate_id']));
                                if (!is_string($rsCriteriaName))
                                {
                                    $rowCriteriaName = mysql_fetch_assoc($rsCriteriaName);
                                    echo "<tr><td class='criteria_name'>" . $rowCriteriaName['criteria_type'] . "</td>";
                                    $rsCountSum = rsSelect(array("COUNT(rate_id)", "SUM(rating_value)"), "version_rating_criteria", array('rate_id=', $row['Rate_id'], 'AND', 'version_id=', get_latest_version($_GET['paper_id'])));
                                    if (!is_string($rsCountSum))
                                    {
                                        $rowCountSum = mysql_fetch_assoc($rsCountSum);
                                        $iCount = $rowCountSum['COUNT(rate_id)'];
                                        $iSum = $rowCountSum['SUM(rating_value)'];
                                        if ($iCount != 0)                           // retreive the average rating for each criteria as it was rated by all other users
                                        {                                           // and advances the progress bar by the average rating value
                                            $dAvg = $iSum / $iCount;
                                            $dBarWidth = ((200 * $dAvg) / 5) . "px";
                                            echo "<td>
                                                    <div class='progress_outer'>
                                                    <div class='progress_inner' style='width: $dBarWidth;'></div>
                                                    </div></td></tr>";
                                        }
                                        else
                                        {
                                            echo"<td><div class='progress_outer'>
                                                    <div class='progress_inner'></div>
                                                    </div></td></tr>";
                                        }
                                    }
                                    else
                                        echo $rsCountSum;
                                }
                                else
                                    echo $rsCriteriaName;
                            }
                            $rsFinalRating = rsSelect("final_rating", "paper", array("paper_id=", $_GET['paper_id']));
                            if (is_string($rsFinalRating))
                                echo $rsFinalRating;
                            else
                            {
                                $row = mysql_fetch_assoc($rsFinalRating);       // get the final rating of the paper and place a progress bar for it

                                $dBarWidth = (($row['final_rating'] * 200) / 5) . "px";
                                echo "<tr><td>Final rating</td>";
                                echo "<td>
                                        <div class='progress_outer'>
                                        <div class='progress_inner' style='width:$dBarWidth;'></div>
                                        </div></td></tr>";
                            }
                        }
                        else
                            echo $rsResult;
                        echo "</table><br/><button id = 'rate_cancel' name = 'rate_cancel'>Cancel</button></div>";
                    }
                    ?>
                    <input type = "hidden" name = "conference_id" id = "conference_id" value = "<?php if (isset($_GET['conference_id'])) echo $_GET['conference_id'];else echo 'null'; ?>"/>
                    <!--hidden field to store the version id of the paper sent to the page by the referrer to be viewed later-->
                    <input type = "hidden" name = "version_id" id = "version_id" value = "<?php
                    require_once "functions.php";
                    if (isset($_GET['paper_id']))
                        echo get_latest_version($_GET['paper_id']);else
                        echo 'null';
                    ?>"/>
                </td>
            </tr>
        </table>
    </body>
</html>